<template>
  <div class="app-container calendar-list-container">
    <el-form :model="formInline" class="demo-ruleForm" size="mini">
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="跟进人次" label-width="80px">
            <el-input-number v-model="formInline.number" style="width: 120px !important;"  @change="formNumber" :min="0" label="描述文字"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="新增时间" label-width="80px">
            <el-date-picker v-model="formInline.date" style="width: 95% !important;" @change="formDate" type="daterange" align="right" unlink-panels
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions2">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="意向等级" label-width="70px">
            <el-select v-model="formInline.industryType" style="width: 500px;" multiple collapse-tags placeholder="请选择分组">
              <el-option style="width: 250px;" v-for="item in infoTabel.intentionLevel" :key="item[1]" :label="item[0]"
                         :value="item[1]"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <avue-crud ref="crud" :page="page" :data="tableData" :table-loading="tableLoading" :option="tableOption"
               @current-change="handleCurrentChange"  @selection-change="handleSelectionChange" @refresh-change="handleRefresh">
      <template slot-scope="scope" slot="wechat">
        <span>微信</span>
      </template>
      <template slot-scope="scope" slot="tel1">
        <span>{{parseTal(scope.row.tel1)}}</span>
      </template>
      <template slot-scope="scope" slot="tel2">
        <span>{{parseTal(scope.row.tel2)}}</span>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="primary" v-if="permissions.sales_publicRepertory_manage_upd" icon="el-icon-edit" size="small"
                   plain @click="followUp(scope.row,scope.index)">领取学员
        </el-button>
        <el-button type="primary" icon="el-icon-search" size="small" plain @click="followUpList(scope.row)">跟进信息
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button v-if="permissions.sales_publicRepertory_manage_distribution"  title="分配" type="primary"  @click="distribution"
                   circle size="small">分配</el-button>
        <el-button v-if="permissions.sales_publicRepertory_manage_receive"  title="领取" type="primary"  @click="receive"
                   circle size="small">领取</el-button>
        <!--<el-button  title="删除" type="danger" icon="el-icon-delete" circle size="small"-->
        <!--@click=""></el-button>-->
        <!--<el-button v-if="qs_intention_customer_followupList" title="跟进信息" type="info" icon="el-icon-tickets"-->
                   <!--@click="handleCalls" circle size="small"></el-button>-->
      </template>


      <template slot-scope="scope" slot="lastFollowUpTime">
        <span>{{ formatDate(scope.row.lastFollowUpTime, 'yyyy-MM-dd hh:mm:ss')}}</span>
      </template>

      <template slot-scope="scope" slot="collectDate">
        <span>{{ formatDate(scope.row.collectDate, 'yyyy-MM-dd hh:mm:ss')}}</span>
      </template>

      <template slot-scope="props" slot="expand">
        <el-form label-position="left" inline class="demo-table-expand">
          <el-row type="flex" class="row-bg">
            <el-col :span="7">
              <el-form-item label="行业类别：">
                <span>{{workingTypeS(props.row.workingType)}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="职位：">
                <span>{{jobTypeS(props.row.jobType)}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="工作区域：">
                <span>{{workingAreaS(props.row.workingArea)}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" class="row-bg">
            <el-col :span="7">
              <el-form-item label="居住区域：">
                <span>{{workingAreaS(props.row.homeArea)}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="跟进次数：">
                <span>{{props.row.callCount}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="详细地址：">
                <span>{{props.row.homeAddress}}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </avue-crud>

    <el-dialog title="跟进信息" :data="tableData" :visible.sync="dialogFormVisible">
      <el-table :data="followUpData" element-loading-text="给我一点时间" border fit
                highlight-current-row style="width: 100%">
        <el-table-column align="center" label="跟进人">
          <template scope="scope">
            <span>{{ createUserS(scope.row.createUser) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="跟进时间">
          <template scope="scope">
            <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="意向等级">
          <template scope="scope">
            <span>{{ intentionLevelS(scope.row.intentionLevel) }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column align="center" label="部门">-->
        <!--<template scope="scope">-->
        <!--<span>{{ scope.row.deptId }}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column align="center" label="备注">
          <template scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination @size-change="handleCallSizeChange" @current-change="handleCallCurrentChange"
                       :current-page.sync="callListQuery.page"
                       :page-sizes="[5,10,20,30, 50]" :page-size="callListQuery.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="callListQuery.total">
        </el-pagination>
      </div>
    </el-dialog>


    <el-dialog title="客户分配" :visible.sync="customerSistribution" @close="cancel">
      <el-form>
        <el-form-item label="选择跟进人" label-width="120px">

          <el-cascader :options="users" v-model="followUpUser"></el-cascader>
          <!--<input type="hidden" v-model="user.followUpUser"/>-->

          <!--<el-select  v-model="followUpUser" placeholder="请选择跟进人" @change="selectChange">-->
            <!--<el-option v-for="item in followUpUserList" :label="item.name" :value="item.userId"></el-option>-->
          <!--</el-select>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sistribution">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchList, sFollowUp, updateToBatch} from '@/api/sales/sales_public_repertory_manage'
  import {getListByStudent} from '@/api/sales/sales_intention_flowup'
  import {tableOption} from '@/const/sales/public_repertory_manage'
  import {getIdNameList, getDeptUserTree} from '@/api/user'
  import {loadByType} from '@/api/dict'
  import {formatDateS} from '@/util/util.js'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  import {mapGetters} from 'vuex'
  import ElRadioGroup from 'element-ui/packages/radio/src/radio-group'

  export default {
    components: {
      ElRadioGroup
    },
    name: 'publicRepertoryManage',
    directives: {
      waves
    },
    data() {
      return {
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        value7: '',
        formInline:{
          number: 0,
          date: null,
          industryType: null
        },
        infoTabel: {
          createUser: [],
          intentionLevel: [],
          jobType: [],
          workingType: [],
          workingArea: []
        },
        users: [],
        tableData: [],
        followUpData: [],
        flagManage: [],
        dialogFormVisible: false,
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        callListQuery: {  // 跟进记录翻页数据
          page: 1,
          limit: 5,
          total: 0,
          student_id: ''
        },
        row: '',
        tableLoading: false,
        tableOption: tableOption,
        selectData: [],
        customerSistribution: false,
        followUpUser: []
      }
    },
    created() {
      this.getList()
      this.initUserDic()
    },
    mounted() {
      this.infoTabelS()
    },
    computed: {
      ...mapGetters(['permissions'])
    },
    methods: {
      // getNodeData(data) {
      //   this.followUpUser.push(data[data.length - 1])
      // },
      initUserDic() {
        getDeptUserTree().then(response => {
          this.users = response.data
        })
      },
      formatDate(date, fromat) {
        if (date != null) {
          return formatDateS(new Date(date), fromat)
        } else {
          return '-'
        }
      },
      resetForm() {
        this.formInline.number = 0
        this.formInline.date = null
        this.formInline.industryType = []
      },
      onSubmit() {
        let quertData = {
          number: this.formInline.number,
          beginDate: null,
          endDate: null,
          page: 1,
          intention_level: null,
          limit: this.page.pageSize
        }
        if (this.formInline.date != null) {
          quertData.beginDate = this.formInline.date[0]
          quertData.endDate = this.formInline.date[1]
        }
        if (this.formInline.industryType!=null && this.formInline.industryType.length > 0) {
          quertData.intention_level = this.formInline.industryType.join(',')
        }
        console.log(quertData)
        fetchList(quertData).then(response => {
          this.tableData = response.data.records
          this.page.total = response.data.total
          this.page.currentPage = 1
          this.tableLoading = false
        })
        console.log(this.formInline)
      },
      formNumber() {
        if (this.formInline.number != null && this.formInline.number != 0) {
          this.formInline.date = null
        }
      },
      formDate() {
        if (this.formInline.date != null) {
          this.formInline.number = null
        }
      },
      receive() {
        if (this.selectData.length === 0) {
          this.$message({
            showClose: true,
            message: '请选择需要领取的客户',
            type: 'warning'
          })
          return
        }
        this.$confirm('确认领取客户 ？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateToBatch(this.selectData, -1).then(() => {
            this.getList()
            this.$message({
              type: 'success',
              message: '领取成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消领取'
          })
        })
      },
      /**
       *
       *  批量分配客户
       *
       */
      sistribution() {
        updateToBatch(this.selectData, this.followUpUser[this.followUpUser.length - 1]).then(response => {
          this.customerSistribution = false
          this.getList()
          this.$message({
            showClose: true,
            message: '分配成功',
            type: 'success'
          })
        })
      },
      /**
       *
       * 选择跟进人
       *selectChange(val) {
      //   this.followUpUser = val
      // },
       */
      //
      /**
       *  分配客户
       *
       */
      distribution() {
        if (this.selectData.length === 0) {
          this.$message({
            showClose: true,
            message: '请选择需要分配的客户',
            type: 'warning'
          })
          return
        }
        this.customerSistribution = true
      },
      /**
       * @title 当前选中的数据
       * @param val 选中的值
       *
       **/
      handleSelectionChange(val) {
        this.selectData = val
      },
      /**
       * @title 翻页
       *
       **/
      handleCurrentChange(val) {
        this.page.currentPage = val
        this.getList()
      },
      infoTabelS() {
        getIdNameList().then(response => {
          this.followUpUserList = response.data
          for (let i = 0; i < response.data.length; i++) {
            this.infoTabel.createUser[i] = {0: response.data[i].username, 1: response.data[i].userId}
          }
        })
        loadByType('intention_level').then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.infoTabel.intentionLevel[i] = {0: response.data[i].label, 1: response.data[i].value}
          }
        })
        loadByType('job_type').then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.infoTabel.jobType[i] = {0: response.data[i].label, 1: response.data[i].value}
          }
        })
        loadByType('working_area').then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.infoTabel.workingArea[i] = {0: response.data[i].label, 1: response.data[i].value}
          }
        })
      },
      createUserS(value) {
        for (let i = 0; i < this.infoTabel.createUser.length; i++) {
          if (this.infoTabel.createUser[i][1] == value) {
            return this.infoTabel.createUser[i][0]
          }
        }
      },
      intentionLevelS(value) {
        for (let i = 0; i < this.infoTabel.intentionLevel.length; i++) {
          if (this.infoTabel.intentionLevel[i][1] == value) {
            return this.infoTabel.intentionLevel[i][0]
          }
        }
      },
      workingTypeS(value) {
        for (let i = 0; i < this.infoTabel.workingType.length; i++) {
          if (this.infoTabel.workingType[i][1] == value) {
            return this.infoTabel.workingType[i][0]
          }
        }
      },
      jobTypeS(value) {
        for (let i = 0; i < this.infoTabel.jobType.length; i++) {
          if (this.infoTabel.jobType[i][1] == value) {
            return this.infoTabel.jobType[i][0]
          }
        }
      },
      workingAreaS(value) {
        for (let i = 0; i < this.infoTabel.workingArea.length; i++) {
          if (this.infoTabel.workingArea[i][1] == value) {
            return this.infoTabel.workingArea[i][0]
          }
        }
      },
      parseTal(value) {
        if (value === null || value === '') {
          return '-'
        } else {
          var length = (value.length / 3).toFixed()
          var zw = ['*', '**', '***', '****']
          return value.substr(0, length) + zw[length - 1] + value.substring(2 * length, value.length)
        }
      },
      getList(boo) {
        this.tableLoading = true

        let quertData = {
          number: this.formInline.number,
          beginDate: null,
          endDate: null,
          page: this.page.currentPage,
          intention_level:null,
          limit: this.page.pageSize
        }
        if (this.formInline.date != null) {
          quertData.beginDate = this.formInline.date[0]
          quertData.endDate = this.formInline.date[1]
        }
        if (this.formInline.industryType!=null && this.formInline.industryType.length > 0) {
          quertData.intention_level = this.formInline.industryType.join(',')
        }
        fetchList(quertData).then(response => {
          this.tableData = response.data.records
          this.page.total = response.data.total
          this.tableLoading = false
          if (boo) {
            this.$notify({
              message: `刷新数据成功`,
              type: 'success'
            })
          }
        })
      },
      handleRefresh() {
        this.getList(true)
      },
      followUp(row, index) {
        sFollowUp(row.fid).then(response => {
          if (response.data.data.data) {
            this.$message({
              showClose: true,
              message: '学员跟进成功!',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message.error(response.data.data.msg)
          }
        })
      },
      followUpList(row) {
        this.row = row
        this.dialogFormVisible = true
        this.callListQuery.student_id = this.row.fid
        getListByStudent(this.callListQuery).then(response => {
          this.followUpData = response.data.records
          this.callListQuery = {
            total: response.data.total,
            limit: response.data.size,
            page: response.data.current
          }
        })
      },
      /**
       *  跟进记录切换每页多少条数据
       * @param val
       */
      handleCallSizeChange(val) {
        this.callListQuery.limit = val
        this.followUpList(this.row)
      },
      /**
       *  跟进记录翻页
       * @param val
       */
      handleCallCurrentChange(val) {
        this.callListQuery.page = val
        this.followUpList(this.row)
      },
      cancel() {
        this.followUpUser = []
        this.customerSistribution = false
      }
    }
  }
</script>
